import {
  Controller,
  Get,
  Post,
  Req,
  Body,
  Redirect,
  Query,
} from '@nestjs/common';
import { UserService } from './../service/UserService';
import { Request } from 'express';
import { User } from 'src/entity/User';
// eslint-disable-next-line @typescript-eslint/no-var-requires
const { getConnection } = require('./../utils/node-mybatis/DB');

@Controller('/user')
export class UserController {
  constructor(private readonly userService: UserService) {}

  @Post('/query')
  async getHello(@Body() catBody: User): Promise<any> {
    console.log('catBody', catBody);
    const { id } = catBody;
    const result = await this.userService.getUser(id);
    console.log('request====', result);
    return {
      success: true,
      data: result,
    };
  }

  @Post('/insert')
  async create(@Body() user: User): Promise<any> {
    console.log('user=', user);
    if (!!!user.username) {
      return 'username 不能为空';
    }
    if (!!!user.sex) {
      return 'sex 不能为空';
    }
    if (!!!user.address) {
      return 'address 不能为空';
    }
    const result = await this.userService.createUser(user);
    console.log('user 创建成功', result);
    return result;
  }

  @Post('/delete')
  async delete(): Promise<any> {
    const connection = await getConnection();
    await connection.beginTransaction();
    try {
      const result1 = await this.userService.delete(connection, '18');
      // throw new Error('xxx错误');
      // const result2 = await this.userService.delete(connection, '20');
      // const result2 = await this.userService.createUser();

      await connection.commit();
      console.log('delete request====', result1);
      return {
        success: true,
        data: [result1],
      };
    } catch (error) {
      connection.rollback();
      console.log(error);
      return error.message;
    }
  }

  /**
   * 默认重定向地址：'https://docs.nestjs.com'；version=5时，
   * 重定向到 'https://docs.nestjs.com/v5/'
   */
  @Get('/docs')
  @Redirect('https://docs.nestjs.com', 302)
  getDocs(@Query('version') version) {
    if (version && version === '5') {
      return { url: 'https://docs.nestjs.com/v5/' };
    }
  }
}
